from rest_framework import serializers
from rest_framework.serializers import ModelSerializer
from article.models import Article
from question.models import Reply, Question, Label
from recruit.models import Enterprise, Recruit
from users.models import User


class ReplySerializer(ModelSerializer):
    '''回复规格表序列化器'''

    user = serializers.PrimaryKeyRelatedField(read_only=True)
    content = serializers.StringRelatedField(read_only=True)

    class Meta:
        model = Reply
        fields = ("id", "content", "createtime", 'problem', "user", 'useful_count', 'type')


class QuestionSerializer(ModelSerializer):
    ''' Question规格表序列化器'''

    class Meta:
        model = Question
        fields = '__all__'

        def __str__(self):
            return self.user


class RecruitSerializer(ModelSerializer):
    class Meta:
        model = Recruit
        fields = '__all__'


class LabelSerializer(ModelSerializer):
    '''Label规格表序列化器'''

    class Meta:
        model = Label
        fields = '__all__'


class ArticleSerializer(ModelSerializer):
    '''文章阅读规格表序列化器'''
    user = serializers.CharField(read_only=True)

    class Meta:
        model = Article
        fields = '__all__'


class EnterpriseSerializer(ModelSerializer):
    '''企业规格表序列化器'''

    class Meta:
        model = Enterprise
        fields = ['id', 'name', 'labels', 'logo', 'recruits', 'summary']


class UserSerializer(ModelSerializer):
    '''用户序列化器'''

    answer_question = serializers.SerializerMethodField()
    username = serializers.CharField(read_only=True)
    questions = QuestionSerializer(many=True)
    labels = LabelSerializer(many=True)
    collected_articles = serializers.SerializerMethodField()
    enterpises = EnterpriseSerializer(many=True)

    class Meta:
        model = User

        fields = '__all__'

    def get_answer_question(self, obj):
        reply = Reply.objects.filter(user=obj)
        return ReplySerializer(reply, many=True).data

    def get_collected_articles(self, obj):
        articles = Article.objects.filter(user=obj)
        return ArticleSerializer(articles, many=True).data
